package org.mineground.commands.irc;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.jibble.pircbot.Colors;
import org.jibble.pircbot.User;
import org.mineground.Main;
import org.mineground.Utilities;
import org.mineground.handlers.irc.CommandExecutor;
import org.mineground.handlers.irc.UserLevel;

public class Give implements CommandExecutor {
    @Override
    public void onCommand(User sender, UserLevel level, String channel, String command, String args[]) {
	if (level.compareTo(UserLevel.IRC_SOP) < 0) {
	    return;
        }

	if (args.length < 3) {
	    Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Usage:" + Colors.NORMAL + " !give [player] [itemID/itemName] [amount]");
	    return;
	}

	Player player = Main.getInstance().getServer().getPlayer(args[0]);
        
        if (player == null) {
            Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Error: That player is not online.");
            return;
        }
        
        if (player.getWorld() == Main.getInstance().getServer().getWorld(Main.getInstance().getConfigHandler().survivalWorldName) || player.getWorld() == Main.getInstance().getServer().getWorld(Main.getInstance().getConfigHandler().survivalNetherWorldName)) {
            Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "YOU FUCKING CHEATER!");
            return;
        }
        
	PlayerInventory inventory;
        Material blockMaterial;
	String blockId = args[1];
        
        int blockAmount = Integer.parseInt(args[2]);

        if (Utilities.isNumeric(blockId)) {
            blockMaterial = Material.getMaterial(Integer.parseInt(blockId));
        }
        
        else {
            blockMaterial = Material.getMaterial(blockId.toUpperCase());
        }

	if (blockMaterial == null) {
	    Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Error: Invalid item, visit http://www.minecraftwiki.net/wiki/Data_values#Block_IDs_.28Minecraft_Beta.29 for more information.");
	    return;
	}

	inventory = player.getInventory();
	ItemStack newItem = new ItemStack(blockMaterial);
	newItem.setAmount(blockAmount);
	inventory.addItem(newItem);

	player.sendMessage(ChatColor.GOLD + sender.getNick() + " has given you " + blockAmount + " of " + blockMaterial.toString().toLowerCase() + ".");
	Main.getInstance().getIRCHandler().sendMessage(channel, Colors.DARK_GREEN + "You have given " + Utilities.fixName(player) + Colors.DARK_GREEN + " " + blockAmount + " of " + blockMaterial.toString().toLowerCase() + ".");
    }
}